package com.elong.businesstravel.base.umeng.socialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.mcrypt.MCrypt;
import com.elong.businesstravel.base.umeng.socialize.adapter.CustomShareAdapter;
import com.elong.businesstravel.base.utils.AppUserId;
import com.elong.businesstravel.base.utils.SaveUserOperate;
import com.elong.businesstravel.include.Version;
import com.elong.businesstravel.protocol.ProtocolDef;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.UMShareMsg;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.UMSsoHandler;
import com.umeng.socialize.controller.UMWXHandler;
import com.umeng.socialize.controller.listener.SocializeListeners.DirectShareListener;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.CircleShareContent;
import com.umeng.socialize.media.MailShareContent;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.SmsShareContent;
import com.umeng.socialize.media.TencentWbShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMVideo;
import com.umeng.socialize.media.WeiXinShareContent;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class CustomShareDialog extends Dialog {

	public static final String WX_APPID = "wx5e33f949aa7dc08b";
	public static final String WX_APPSECRET = "f746b0bd37eea2c65f17285355e5dc2c";
	private static final Integer[] ICON_ID = {
			R.drawable.ic_wechat,
			R.drawable.ic_wxcircle,
			R.drawable.ic_gmail,
			R.drawable.ic_sina,
			R.drawable.ic_qq, R.drawable.ic_sms, };
	private static final String[] NAME = { "微信", "朋友圈", "邮件", "新浪微博", "QQ",
			"短信" };

	private Context mContext;

	private UMSocialService mUmSocialService;
	public IWXAPI api;

	private GridView mGridView;
	private CustomShareAdapter mCustomShareAdapter;

	/** 微信 */
	private UMWXHandler mWxHandler;
	/** 朋友圈 */
	private UMWXHandler mCircleHandler;

	private TextView mTitleTextView;
	private TextView mDescTextView;

	public CustomShareDialog(Context context) {
		super(context);
		init(context);
	}

	public CustomShareDialog(Context context, int theme) {
		super(context, theme);
		init(context);
	}

	public CustomShareDialog(Context context, boolean cancelable,
			OnCancelListener cancelListener) {
		super(context, cancelable, cancelListener);
		init(context);
	}

	public static CustomShareDialog getCustomShareDialog(Context context,
			int theme) {
		return new CustomShareDialog(context, theme);
	}

	private void init(Context context) {

		Window window = getWindow();
		window.setGravity(Gravity.BOTTOM);

		setContentView(R.layout.dialog_share);

		mContext = context;

		// TextView descTextView = (TextView)findViewById(R.id.descTextView);
		// descTextView.setText();
		mDescTextView = (TextView) findViewById(R.id.descTextView);
		mTitleTextView = (TextView) findViewById(R.id.titleTextView);

		mUmSocialService = UMServiceFactory.getUMSocialService(
				Version.productName, RequestType.SOCIAL);
		mUmSocialService.getConfig().setSsoHandler(new TencentWBSsoHandler());
		mUmSocialService.getConfig().setSsoHandler(new SinaSsoHandler());
		mUmSocialService.getConfig().supportQQPlatform((Activity) mContext,
				ProtocolDef.SHARE_URL);
		mWxHandler = mUmSocialService.getConfig().supportWXCirclePlatform(
				mContext, WX_APPID, ProtocolDef.SHARE_URL);
		mCircleHandler = mUmSocialService.getConfig().supportWXPlatform(
				mContext, WX_APPID, ProtocolDef.SHARE_URL);

		// mWxHandler.setWXTitle("微信分享");
		// mCircleHandler.setCircleTitle("朋友圈分享");

		mGridView = (GridView) findViewById(R.id.gridView);
		mCustomShareAdapter = new CustomShareAdapter(mContext, ICON_ID, NAME);
		mGridView.setAdapter(mCustomShareAdapter);

		api = WXAPIFactory.createWXAPI(mContext, WX_APPID);

		setListener();

		setCanceledOnTouchOutside(true);
		
		DebugLog.setTag(CustomShareDialog.class.toString());
	}

	private void setListener() {
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				int iconId = (Integer) view.getTag();
				if (iconId == R.drawable.ic_sina) {
					DebugLog.logI("新浪微博");
					// 参数1为Context类型对象， 参数2为要分享到的目标平台， 参数3为分享操作的回调接口
					mUmSocialService.postShare(mContext, SHARE_MEDIA.SINA,
							new SnsPostListener() {
								@Override
								public void onStart() {
									// Toast.makeText(mContext, "开始分享.",
									// Toast.LENGTH_SHORT).show();
//									 HandlerToastUI.getHandlerToastUI(mContext,
//									 "开始分享");
								}

								@Override
								public void onComplete(SHARE_MEDIA platform,
										int eCode, SocializeEntity entity) {
									if (eCode == 200) {
										// Toast.makeText(mContext, "分享成功.",
										// Toast.LENGTH_SHORT).show();
//										 HandlerToastUI.getHandlerToastUI(
//										 mContext, "分享成功.");
									} else {
										String eMsg = "";
										if (eCode == -101) {
											eMsg = "没有授权";
										}
//										 Toast.makeText(mContext, "分享失败[" +
//										 eCode + "] " +
//										 eMsg,Toast.LENGTH_SHORT).show();
//										 HandlerToastUI.getHandlerToastUI(
//										 mContext, "分享失败[" +
//												 eCode + "] " +
//												 eMsg);
									}
								}
							});
				} else if (iconId ==  R.drawable.ic_gmail) {
					DebugLog.logI("邮件");

					// 参数1为Context类型对象， 参数2为要分享到的目标平台， 参数3为分享操作的回调接口
					mUmSocialService.postShare(mContext, SHARE_MEDIA.EMAIL,
							new SnsPostListener() {
								@Override
								public void onStart() {
									// Toast.makeText(mContext, "开始分享.",
									// Toast.LENGTH_SHORT).show();
									// HandlerToastUI.getHandlerToastUI(mContext,
									// "开始分享");
								}

								@Override
								public void onComplete(SHARE_MEDIA platform,
										int eCode, SocializeEntity entity) {
									if (eCode == 200) {
										// Toast.makeText(mContext, "分享成功.",
										// Toast.LENGTH_SHORT).show();
										// HandlerToastUI.getHandlerToastUI(
										// mContext, "分享成功.");
									} else {
										String eMsg = "";
										if (eCode == -101) {
											eMsg = "没有授权";
										}
										// Toast.makeText(mContext, "分享失败[" +
										// eCode + "] " +
										// eMsg,Toast.LENGTH_SHORT).show();
										// HandlerToastUI.getHandlerToastUI(
										// mContext, eMsg);
									}
								}
							});

				} else if (iconId ==  R.drawable.ic_wechat) {
					DebugLog.logI("微信");

					if (!isWeiXinShare()) {
						return;
					}
					// 参数1为Context类型对象， 参数2为要分享到的目标平台， 参数3为分享操作的回调接口
					mUmSocialService.postShare(mContext, SHARE_MEDIA.WEIXIN,
							new SnsPostListener() {
								@Override
								public void onStart() {
									// Toast.makeText(mContext, "开始分享.",
									// Toast.LENGTH_SHORT).show();
									// HandlerToastUI.getHandlerToastUI(mContext,
									// "开始分享");
								}

								@Override
								public void onComplete(SHARE_MEDIA platform,
										int eCode, SocializeEntity entity) {
									if (eCode == 200) {
										// Toast.makeText(mContext, "分享成功.",
										// Toast.LENGTH_SHORT).show();
										// HandlerToastUI.getHandlerToastUI(
										// mContext, "分享成功.");
									} else {
										String eMsg = "";
										if (eCode == -101) {
											eMsg = "没有授权";
										}
										// Toast.makeText(mContext, "分享失败[" +
										// eCode + "] " +
										// eMsg,Toast.LENGTH_SHORT).show();
										// HandlerToastUI.getHandlerToastUI(
										// mContext, eMsg);
									}
								}
							});
					//
					// boolean sendReq = sendByWX(api, mTranWeiXinShareContent,
					// false);
					//
					// if (sendReq) {// 发送分享统计信息给Umeng
					// sendUmengStatistical(mTranWeiXinShareContent,
					// "wxsession");
					// // HandlerToastUI.getHandlerToastUI(mContext, "发送成功");
					// } else {
					// // HandlerToastUI.getHandlerToastUI(mContext, "发送失败");
					// }
				} else if (iconId ==  R.drawable.ic_wxcircle) {
					DebugLog.logI("朋友圈");

					if (!isWeiXinShare()) {
						return;
					}
					// 参数1为Context类型对象， 参数2为要分享到的目标平台， 参数3为分享操作的回调接口
					mUmSocialService.postShare(mContext,
							SHARE_MEDIA.WEIXIN_CIRCLE, new SnsPostListener() {
								@Override
								public void onStart() {
									// Toast.makeText(mContext, "开始分享.",
									// Toast.LENGTH_SHORT).show();
//									HandlerToastUI.getHandlerToastUI(mContext,
//											"开始分享");
								}

								@Override
								public void onComplete(SHARE_MEDIA platform,
										int eCode, SocializeEntity entity) {
									if (eCode == 200) {
										// Toast.makeText(mContext, "分享成功.",
										// Toast.LENGTH_SHORT).show();
//										HandlerToastUI.getHandlerToastUI(
//												mContext, "分享成功.");
									} else {
										String eMsg = "";
										if (eCode == -101) {
											eMsg = "没有授权";
										}
										// Toast.makeText(mContext, "分享失败[" +
										// eCode + "] " +
										// eMsg,Toast.LENGTH_SHORT).show();
//										HandlerToastUI.getHandlerToastUI(
//												mContext, eMsg);
									}
								}
							});
					// boolean sendReq = sendByWX(api, mTranCircleShareContent,
					// true);
					//
					// if (sendReq) {// 发送分享统计信息给Umeng
					// sendUmengStatistical(mTranCircleShareContent,
					// "wxtimeline");
					// // HandlerToastUI.getHandlerToastUI(mContext, "发送成功");
					// } else {
					// // HandlerToastUI.getHandlerToastUI(mContext, "发送失败");
					// }
				} else if (iconId == R.drawable.ic_sms) {
					DebugLog.logI("短信");
					// ToolUtil.sendMessageActivity(mContext,
					// mTranSmsShareContent.smsShareContentString);
					// 参数1为Context类型对象， 参数2为要分享到的目标平台， 参数3为分享操作的回调接口
					mUmSocialService.postShare(mContext, SHARE_MEDIA.SMS,
							new SnsPostListener() {
								@Override
								public void onStart() {
									// Toast.makeText(mContext, "开始分享.",
									// Toast.LENGTH_SHORT).show();
									// HandlerToastUI.getHandlerToastUI(mContext,
									// "开始分享");
								}

								@Override
								public void onComplete(SHARE_MEDIA platform,
										int eCode, SocializeEntity entity) {
									if (eCode == 200) {
										// Toast.makeText(mContext, "分享成功.",
										// Toast.LENGTH_SHORT).show();
										// HandlerToastUI.getHandlerToastUI(
										// mContext, "分享成功.");
									} else {
										String eMsg = "";
										if (eCode == -101) {
											eMsg = "没有授权";
										}
										// Toast.makeText(mContext, "分享失败[" +
										// eCode + "] " +
										// eMsg,Toast.LENGTH_SHORT).show();
										// HandlerToastUI.getHandlerToastUI(
										// mContext, eMsg);
									}
								}
							});
				} else if (iconId == R.drawable.ic_qq) {
					DebugLog.logI("QQ");
					mUmSocialService.postShare(mContext, SHARE_MEDIA.QQ,
							new SnsPostListener() {
								@Override
								public void onStart() {
									// Toast.makeText(mContext, "开始分享.",
									// Toast.LENGTH_SHORT).show();
									// HandlerToastUI.getHandlerToastUI(mContext,
									// "开始分享");
								}

								@Override
								public void onComplete(SHARE_MEDIA platform,
										int eCode, SocializeEntity entity) {
									if (eCode == 200) {
										// Toast.makeText(mContext, "分享成功.",
										// Toast.LENGTH_SHORT).show();
										// HandlerToastUI.getHandlerToastUI(
										// mContext, "分享成功.");
									} else {
										String eMsg = "";
										if (eCode == -101) {
											eMsg = "没有授权";
										}
										// Toast.makeText(mContext, "分享失败[" +
										// eCode + "] " +
										// eMsg,Toast.LENGTH_SHORT).show();
										// HandlerToastUI.getHandlerToastUI(
										// mContext, eMsg);
									}
								}
							});
				}

				cancel();

			}
		});

	}

	public void setTitleMessage(String titleString, String descString) {
		mTitleTextView.setText(titleString);
		mDescTextView.setText(descString);
		ViewGroup topLayout = (ViewGroup) findViewById(R.id.topLayout);
		topLayout.setVisibility(View.VISIBLE);
	}

	/**
	 * 设置分享内容,不需要的传null
	 * 
	 */
	public void setShareContent(WeiXinShareContent weiXinShareContent,
			CircleShareContent circleShareContent,
			SinaShareContent sinaShareContent,
			MailShareContent mailShareContent, QQShareContent qqShareContent,
			SmsShareContent smsShareContent) {
		if (null != weiXinShareContent) {
			mUmSocialService.setShareMedia(weiXinShareContent);
		}
		if (null != circleShareContent) {
			mUmSocialService.setShareMedia(circleShareContent);
		}
		if (null != sinaShareContent) {
			mUmSocialService.setShareMedia(sinaShareContent);
		}
		if (null != mailShareContent) {
			mUmSocialService.setShareMedia(mailShareContent);
		}
		if (null != qqShareContent) {
			mUmSocialService.setShareMedia(qqShareContent);
		}
		if (null != smsShareContent) {
			mUmSocialService.setShareMedia(smsShareContent);
		}
		// // 视频分享，并且设置了腾讯微博平台的文字内容
		// UMVideo umVedio = new UMVideo(
		// "http://v.youku.com/v_show/id_XNTc0ODM4OTM2.html");
		// umVedio.setThumb("http://www.umeng.com/images/pic/banner_module_social.png");
		// umVedio.setTitle("友盟社会化组件视频");
		// TencentWbShareContent tencentContent = new
		// TencentWbShareContent(umVedio);
		// // 设置分享到腾讯微博的文字内容
		// tencentContent.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能，腾讯微博");
		// // 设置分享到腾讯微博的多媒体内容
		// mUmSocialService.setShareMedia(tencentContent);
		//
		// SinaShareContent sinaShareContent = new SinaShareContent("新浪微博");
		// mUmSocialService.setShareMedia(sinaShareContent);
		//
		// WeiXinShareContent weiXinShareContent = new
		// WeiXinShareContent("微信分享");
		// mUmSocialService.setShareMedia(weiXinShareContent);
		// CircleShareContent circleShareContent = new
		// CircleShareContent("朋友圈");
		// mUmSocialService.setShareMedia(circleShareContent);

	}

	/**
	 * 在他所在的Activity中调用,用来新浪微博的sso
	 * 
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		/**
		 * 使用SSO必须添加，指定获取授权信息的回调页面，并传给SDK进行处理
		 */
		UMSsoHandler ssoHandler = mUmSocialService.getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	/**
	 * 是否可以分享微信和朋友圈
	 * 
	 * @return false不能分享，true可以分享
	 */
	private boolean isWeiXinShare() {
		if (!api.isWXAppInstalled()) {
			HandlerToastUI.getHandlerToastUI(mContext, "你还没有安装微信");
			return false;
		} else if (!api.isWXAppSupportAPI()) {
			HandlerToastUI.getHandlerToastUI(mContext, "你安装的微信版本不支持当前API");
			return false;
		}

		return true;
	}

}
